//
//  HLBShopMerchantVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/12/6.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "HLBShopMerchantVC.h"

@interface HLBShopMerchantVC ()<UICollectionViewDelegate,UICollectionViewDataSource,
UIActionSheetDelegate>{
    BOOL _isEdit;
}

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *albumImgListArray;

@end

@implementation HLBShopMerchantVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitle:_editDataModel.album_name titleColor:kBlackColor font:font17];
    
    [self getAlbumImgList];
    [self rightNavItem];
}

- (void)rightNavItem{
    
    __weak typeof (self)weakself = self;
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [rightBtn setTitle:@"取消" forState:UIControlStateSelected];
    [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [rightBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton* sender) {
        rightBtn.selected = !rightBtn.selected;
        _isEdit = rightBtn.selected;
        [weakself.collectionView reloadData];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
}

#pragma  mark ========网络加载.....========
- (void)getAlbumImgList{
    //__weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumImgList" isactive:YES parameter:@{@"agent_album_id":_editDataModel.albumID} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
        _albumImgListArray = responseObj.mutableCopy;
        
        [self.view addSubview:self.collectionView];
      //  [weakself.collectionView reloadData];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

#pragma  mark ========懒加载========
- (UICollectionView *)collectionView{
    if(_collectionView == nil){
         UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        // 设置collectionView的滚动方向，需要注意的是如果使用了collectionview的headerview或者footerview的话， 如果设置了水平滚动方向的话，那么就只有宽度起作用了了
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 2;// 垂直方向的间距
        layout.minimumLineSpacing = 2; // 水平方向的间距

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 5, SCREEN_W, SCREEN_H-HLBTabHeight-NavigationHeight-5) collectionViewLayout:layout];
        _collectionView.backgroundColor = ControllerColor;
        _collectionView.delegate=self;
        _collectionView.dataSource=self;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    }
    
    return _collectionView;
}

#pragma  mark ========UICollectionViewDelegate,UICollectionViewDataSource========
//一共有多少个组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//每一组有多少个cell
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _albumImgListArray.count+1;
}
//每一个cell是什么
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }

    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.frame = cell.bounds;
    [cell.contentView addSubview:imageV];
    
    UIButton *delImgBtn = [[UIButton alloc] init];
    [delImgBtn setImage:[UIImage imageNamed:@"edit_nav_icon4_default_nor"] forState:UIControlStateNormal];
    delImgBtn.tag = indexPath.row;
    delImgBtn.frame = CGRectMake(cell.width-GETWITH(40), 0, GETWITH(40), GETWITH(40));
    [delImgBtn addTarget:self action:@selector(delalbumImg:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:delImgBtn];
    
    if(_isEdit){
        delImgBtn.hidden = NO;
    }else{
       delImgBtn.hidden = YES;
    }
    
    if(indexPath.row == _albumImgListArray.count){
        [delImgBtn removeFromSuperview];
        imageV.image = [UIImage imageNamed:@"photo_bg2_default"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseImage)];
        imageV.userInteractionEnabled = YES;
        [imageV addGestureRecognizer:tap];
    }else{
        NSDictionary *dic = _albumImgListArray[indexPath.row];
        imageV.userInteractionEnabled = NO;
        [imageV sd_setImageWithURL:[NSURL URLWithString:dic[@"img_path"]] placeholderImage:[UIImage imageNamed:@"photo_bg12_default"]];
    }
    
    return cell;
}
//每一个分组的上左下右间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(2, 2, 0, 0);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_W-12)/4, (SCREEN_W-12)/4);
}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //cell被电击后移动的动画
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
}

#pragma  mark ========选择相片========
- (void)chooseImage{
    UIActionSheet *sheet;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    sheet.tag = 225;
    [sheet showInView:self.view];
}

#pragma  mark ========UIActionSheetDelegate========
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(actionSheet.tag == 225){
        NSUInteger sourceType = 0;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            switch (buttonIndex) {
                case 0:
                    //取消
                    return;
                    break;
                case 1:
                    //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 2:
                    //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    break;
            }
        }else{
            if(buttonIndex==0){
                return;
            }else{
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.navigationBar.translucent = NO;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

#pragma  mark ========UIImagePickerControllerDelegate========
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *newImg = [info objectForKey:UIImagePickerControllerEditedImage];
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] uploadImages:Request_POST URL:@"/ShopApi/Public/imgUpload" isactive:NO imageData:@[newImg] imgfileName:@"img_file" parameter:@{@"img_path":@"GOODS/"} successBlock:^(PPHttpRequest *request, id responseObj) {
        [weakself albumImgSaveAction:responseObj[@"url"]];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)albumImgSaveAction:(NSString *)imgUrl{
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumImgSave" isactive:YES parameter:@{@"agent_album_id":_editDataModel.albumID,@"is_head":@"0",@"img_path":imgUrl} successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [_albumImgListArray insertObject:responseObj atIndex:0];
        [weakself.collectionView reloadData];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
    
}

- (void)delalbumImg:(UIButton *)btn{
    NSDictionary *dic = _albumImgListArray[btn.tag];
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumImgSave" isactive:YES parameter:@{@"agent_album_id":_editDataModel.albumID,@"is_head":@"0",@"img_path":dic[@"img_path"],@"agent_album_img_id":dic[@"id"],@"is_delete":@"1"} successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [_albumImgListArray removeObject:dic];
        [weakself.collectionView reloadData];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}


@end
